import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 修复相同地址反复跳转问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

// 书写路由映射
const routes = [
  {
    name: 'login',
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    // name: 'layout',  // 如果一级路由有默认打开的子路由，那么一级路由命名没有意义！
    path: '/',
    component: () => import('@/views/layout'),
    children:[
      {
        path:'/',
        name:'home',
        component: ()=> import('@/views/home')
      },
      {
        path:'/qa',
        name:'qa',
        component: ()=> import('@/views/qa')
      },
      {
        path:'/video',
        name:'video',
        component: ()=> import('@/views/video')
      },
      {
        path:'/user',
        name:'user',
        component: ()=> import('@/views/user')
      }
    ]
  },
  {
    path:'/lishi',
    name:'lishi',
    component: ()=> import('@/views/user/lishi'),
    meta:{
      needLogin:true
    }
  },
  {
    path:'/shoucang',
    name:'shoucang',
    component: ()=> import('@/views/user/shoucang'),
    meta:{
      needLogin:true
    }
  },
  {
    path:'/search',
    name:'search',
    component: ()=> import('@/views/search'),
  },
  {
    path:'/article/:articleId',
    name:'article',
    props:true,  // 解耦路由数据
    component: ()=> import('@/views/article'),
  },
  {
    path:'/profile',
    name:'profile',
    component: ()=> import('@/views/user-profile'),
    meta:{
      needLogin:true
    }
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫
router.beforeEach((to,from,next)=>{
  // 页面是否需要登录才可以看到
  if(to.meta.needLogin){
    // 判断是否登录了
    if(store.state.user){
      next()
    }else{
      next('/login?redirect='+to.path)
    }
  }else{
    next()
  }
})

/*
思路： 给需要登录的才能看到的页面的路由加上一个元信息，增加一个needLogin字段，如果有这个字段说明
该页面是需要登录才可以看到的！
*/

export default router
